package com.demo.多线程;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Program: java
 * @ClassName Ticket
 * @Author: liutao
 * @Description: 并发买票：CAS
 * @Create: 2023-10-26 22:48
 * @Version 1.0
 **/


public class CasTicket implements Runnable {
    private static final AtomicInteger ticketNum = new AtomicInteger(10);

    public static void main(String[] args) {
        CasTicket ticket = new CasTicket();
        new Thread(ticket, "小明").start();
        new Thread(ticket, "小红").start();
        new Thread(ticket, "李白").start();
    }

    @Override
    public void run() {
        try {
            buy();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

    }

    private void buy() throws InterruptedException {
        while (ticketNum.get() > 0) {
            int currentTicketNum = ticketNum.get();
            if (ticketNum.compareAndSet(currentTicketNum, currentTicketNum - 1)) {
                System.out.println(Thread.currentThread().getName() + "抢到了第" + currentTicketNum + "票");
                Thread.sleep(100);
            }
        }
        System.out.println(Thread.currentThread().getName() +"未抢到，票已售完");
    }
}
